/**
 * Created by wzq on 15-4-23.
 */
define(['jquery', 'js/configAmd'], function ($, config) {
    var myApi = {};

    // cb(errmsg, okResponse)
    myApi.getAdminList = function (cb) {
        $.ajax({
            url: config.getUrlAdminList(),
            type: 'GET',
            success: function (res) {
                cb(null, res);
            },
            fail: function (xhr) {
                cb(xhr.responseText);
            }
        });
    };

    myApi.getAdminOne = function (id, cb) {
        $.ajax({
            url: config.getUrlAdminOne(id),
            type: 'GET',
            success: function (res) {
                cb(null, res);
            },
            fail: function (xhr) {
                cb(xhr.responseText);
            }
        });
    };

    // 登录接口
    myApi.login = function (formData, cb) {
        $.ajax({
            url: config.getHost() + "/api/v1/admin/login",
            type: "POST",
            headers: {"Content-Type": "application/json;charset=UTF-8"},
            data: JSON.stringify(formData),
            success: function (res) {
                cb(null, res);
            },
            error: function (xhr) {
                cb(xhr.responseText);
            }
        });
    };

    /**
     * 上传文件接口
     * @param fileArr array[blobData]
     * @param cb(errMsg, array[{fileName:xx,index:xx,url:xx}]
     */
    myApi.uploadFiles = function (fileArr, cb) {
        function uploadOneFile(blobData, succ, fail) {
            console.log('uploadOneFile');
            var formData = new FormData();
            formData.append("fileBlob", blobData);

            $.ajax({
                url: config.getHost() + "/api/v1/upload",
                type: "POST",
                processData: false,
                contentType: false,
                data: formData,
                success: succ,
                error: fail
            });
        }

        var count = 0;
        var maxCount = fileArr.length;
        var urlList = [];

        function uploadAll(succ, fail) {
            if (count >= maxCount) {
                return succ();
            }

            var blobData = fileArr[count];
            uploadOneFile(blobData, function (res) {
                var url = JSON.parse(res).url;
                urlList.push({index: count, url: url, name: blobData.name});
                count++;
                uploadAll(succ, fail);
            }, fail);
        }

        uploadAll(function () {
            cb(null, urlList);
        }, function (xhr) {
            cb(xhr.responseText);
        });
    };

    /**
     * 返回promise对象
     * @param fileArr
     * @returns {Promise}
     */
    myApi.uploadFilesV2 = function (fileArr) {
        var requests = [];
        var len = fileArr.length;
        fileArr.forEach(function (item) {
            var formData = new FormData();
            formData.append("fileBlob", item);
            var req = $.ajax({
                url: config.getHost() + "/api/v1/upload",
                type: "POST",
                processData: false,
                contentType: false,
                data: formData
            });
            requests.push(req);
        });


        return new Promise(function (resolve, reject) {
            $.when.apply($, requests).done(function () {
                var list = [];
                if (len <= 1) {
                    $.each(arguments, function (i, data) {
                        console.log(typeof data);
                        if (i === 0) list.push({
                            url: JSON.parse(data).url,
                            index: i,
                            name: fileArr[i].name
                        });
                    });
                } else {
                    $.each(arguments, function (j, data) {
                        $.each(data, function (i, dataItem) {
                            if (i === 0) list.push({
                                url: JSON.parse(dataItem).url,
                                index: j,
                                name: fileArr[j].name
                            });
                        });
                    });
                }

                return resolve(list);
            }).fail(function (xhr) {
                return reject(xhr.responseText);
            });
        });
    };


    // 发表一个分享
    myApi.postShare = function (obj, cb) {
        $.ajax({
            url: config.getHost() + "/api/v1/share",
            type: "POST",
            headers: {"Content-Type": "application/json;charset=UTF-8"},
            data: JSON.stringify(obj),
            success: function (res) {
                cb(null, res);
            },
            error: function (xhr) {
                cb(xhr.responseText);
            }
        });
    };

    // 发表一个分享 promise
    myApi.postShareV2 = function (obj) {
        //console.log("postShareV2");
        //console.log(obj);
        return new Promise(function (resolve, reject) {
            $.ajax({
                url: config.getHost() + "/api/v1/share",
                type: "POST",
                headers: {"Content-Type": "application/json;charset=UTF-8"},
                data: JSON.stringify(obj)
            }).done(function (res) {
                return resolve(res);
            }).fail(function (xhr) {
                return reject(xhr.responseText);
            });
        });
    };

    return myApi;
});